<template>
  <n-card title="智能对话">
    <n-space vertical>
      <!-- 当前应用Agent提示 -->
      <n-alert type="info" v-if="currentAgent">
        当前对话Agent: <strong>{{ currentAgent.name }}</strong> - {{ currentAgent.description }}
        <template #action>
          <n-button text @click="goToAgentManagement" type="primary">管理Agent</n-button>
        </template>
      </n-alert>
      <n-alert type="warning" v-else>
        未选择对话Agent，请先在<strong>AI Agent管理</strong>中创建并应用一个Agent
        <template #action>
          <n-button text @click="goToAgentManagement" type="primary">去设置</n-button>
        </template>
      </n-alert>

      <div class="chat-container">
        <div class="messages" ref="messagesContainer">
          <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.type]">
            <div class="message-content">{{ msg.content }}</div>
            <div class="message-time">{{ msg.time }}</div>
          </div>
          <div v-if="loading" class="message bot loading">
            <div class="message-content">思考中...</div>
          </div>
        </div>
        
        <div class="input-area">
          <n-input 
            v-model:value="inputMessage" 
            placeholder="输入您的问题..."
            @keyup.enter="sendMessage"
            :disabled="!currentAgent || loading"
            type="textarea"
            :rows="3"
          >
            <template #suffix>
              <n-button 
                @click="sendMessage" 
                type="primary" 
                :disabled="!currentAgent || loading || !inputMessage.trim()"
                :loading="loading"
              >
                发送
              </n-button>
            </template>
          </n-input>
        </div>
      </div>
    </n-space>
  </n-card>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { NCard, NSpace, NAlert, NInput, NButton, useMessage } from 'naive-ui'
import { flowAPI } from '@/utils/api.js'

const router = useRouter()
const message = useMessage()
const messagesContainer = ref(null)

const inputMessage = ref('')
const messages = ref([])
const loading = ref(false)
const currentAgent = ref(null)

// 获取当前时间
const getCurrentTime = () => {
  return new Date().toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || !currentAgent.value || loading.value) return

  const userMessage = {
    type: 'user',
    content: inputMessage.value,
    time: getCurrentTime()
  }

  messages.value.push(userMessage)
  const userInput = inputMessage.value
  inputMessage.value = ''
  loading.value = true

  // 滚动到底部
  scrollToBottom()

  try {
    console.log('开始发送消息，当前Agent:', currentAgent.value)

    // 检查必要的配置
    if (!currentAgent.value.apiConfig?.apiKey) {
      throw new Error('API密钥未设置')
    }
    if (!currentAgent.value.baseModel) {
      throw new Error('模型未设置')
    }

    // 构建完整的系统提示词（包含规则集）
    const buildSystemPrompt = () => {
      let systemPrompt = currentAgent.value.systemPrompt || '你是一个有帮助的AI助手。'
      
      // 如果有规则集，添加到系统提示词中
      if (currentAgent.value.rules && currentAgent.value.rules.length > 0) {
        const enabledRules = currentAgent.value.rules
          .filter(rule => rule.enabled)
          .map(rule => {
            const priorityText = rule.priority === 'high' ? '【重要规则】' : 
                               rule.priority === 'medium' ? '【一般规则】' : '【参考规则】'
            return `${priorityText} ${rule.content}`
          })
        
        if (enabledRules.length > 0) {
          systemPrompt += '\n\n请严格遵守以下规则：\n' + enabledRules.join('\n')
        }
      }
      
      return systemPrompt
    }

    // 构建对话历史
    const chatMessages = [
      { role: 'system', content: buildSystemPrompt() },
      ...messages.value
        .filter(msg => msg.type === 'user' || msg.type === 'assistant')
        .map(msg => ({
          role: msg.type === 'user' ? 'user' : 'assistant',
          content: msg.content
        })),
      { role: 'user', content: userInput }
    ]

    console.log('构建的消息历史:', chatMessages)

    // 调用API
    const response = await flowAPI.chatCompletions(
      currentAgent.value.apiConfig.apiKey.trim(), // 去除可能的空格
      {
        model: currentAgent.value.baseModel,
        messages: chatMessages,
        temperature: currentAgent.value.temperature,
        max_tokens: currentAgent.value.apiConfig.max_tokens,
        baseURL: currentAgent.value.apiConfig.baseURL
      }
    )

    const botMessage = {
      type: 'assistant',
      content: response,
      time: getCurrentTime()
    }

    messages.value.push(botMessage)
  } catch (error) {
    console.error('发送消息错误:', error)
    const errorMessage = {
      type: 'assistant',
      content: `抱歉，对话出现错误: ${error.message}`,
      time: getCurrentTime()
    }
    messages.value.push(errorMessage)
    message.error(`对话失败: ${error.message}`)
  } finally {
    loading.value = false
    scrollToBottom()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 跳转到Agent管理
const goToAgentManagement = () => {
  router.push('/ai-agent')
}

// 初始化加载当前应用的Agent
onMounted(() => {
  const savedAgent = localStorage.getItem('globalAgent')
  if (savedAgent) {
    try {
      currentAgent.value = JSON.parse(savedAgent)
      console.log('加载的Agent:', currentAgent.value)
      
      // 添加欢迎消息
      messages.value.push({
        type: 'assistant',
        content: `您好！我是${currentAgent.value.name}，${currentAgent.value.description}。有什么可以帮您的？`,
        time: getCurrentTime()
      })
    } catch (error) {
      console.error('解析Agent数据错误:', error)
      message.error('加载Agent配置失败')
    }
  }
})
</script>

<style scoped>
.chat-container {
  height: 600px;
  display: flex;
  flex-direction: column;
}

.messages {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 16px;
  padding: 8px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.message {
  margin: 12px 0;
  padding: 12px;
  border-radius: 8px;
  max-width: 85%;
}

.message.user {
  background: #1890ff;
  color: white;
  margin-left: auto;
}

.message.bot {
  background: #f0f0f0;
  color: #333;
}

.message.loading {
  background: #f8f8f8;
  color: #999;
  font-style: italic;
}

.message-content {
  margin-bottom: 4px;
  white-space: pre-wrap;
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
  text-align: right;
}

.input-area {
  display: flex;
  gap: 8px;
}
</style>